package com.strutor.likou.lstack;

import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 使用队列实现栈的下列操作：
 *
 * push(x) -- 元素 x 入栈
 * pop() -- 移除栈顶元素
 * top() -- 获取栈顶元素
 * empty() -- 返回栈是否为空
 * */
public class QueueStack {


    private Queue<Integer> data;
    private Queue<Integer> helper;

    public QueueStack() {
        data = new LinkedBlockingDeque<>();
        helper = new LinkedBlockingDeque<>();
    }

    /** Push element x onto stack. */
    public void push(int x) {
        data.offer(x);
    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        while(data.size()>1){
            helper.offer(data.poll());
        }
        int ret = data.poll();
        data = helper;
        return ret;
    }

    /** Get the top element. */
    public int top() {
        while(data.size()>1){
            helper.offer(data.poll());
        }
        int ret = data.peek();
        data = helper;
        return ret;
    }

    /** Returns whether the stack is empty. */
    public boolean empty() {
        return data.isEmpty();
    }
}
